<template>
  <div class="search">
    <div class="container">
      <div class="corner"><router-link to="/">首页</router-link> > 搜索</div>
      <div class="search-box">
        <div class="from">
          <el-form
            ref="ruleForm"
            label-width="auto"
            class="demo-ruleForm"
          >
            <el-form-item class="input">
              <span slot="label"><span class="required-icon">收货地址：</span></span>
              <span @click="openMap">
                <el-input v-if="ruleForm.address.addressTitle" v-model="ruleForm.address.addressTitle" type="text" placeholder="点击选择收货地址">
                  <i slot="prefix" class="iconfont icon-site site" />
                </el-input>
                <el-input v-else v-model="ruleForm.address.receiveAddress" type="text" placeholder="点击选择收货地址">
                  <i slot="prefix" class="iconfont icon-site site" />
                </el-input>
              </span>
            </el-form-item>
            <el-form-item id="main-category-select">
              <span slot="label"><span class="required-icon">主分类：</span></span>
              <el-select v-model="ruleForm.mainCategoryVal" placeholder="请选择主分类" value-key="id" @visible-change="mainCategoryItemShow">
                <el-option
                  v-for="item in mainCategoryList"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.categoryName }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.categoryName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item id="sub-category-select">
              <span slot="label"><span class="required-icon">子分类：</span></span>
              <el-select v-model="ruleForm.subCategoryVal" value-key="id" placeholder="请选择子分类" @visible-change="subCategoryItemShow">
                <el-option
                  v-for="item in subCategoryList"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.categoryName }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.categoryName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProa" id="category-prop-select1">
              <span slot="label"><span class="required-icon">{{ ruleForm.subCategoryVal.standardProa }}：</span></span>
              <el-select v-model="ruleForm.attributeVal[0]" :loading="attributeLoading[0]" placeholder="请选择属性" value-key="id" @visible-change="cateProp1ItemShow">
                <el-option
                  v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (1)), false)"
                  :key="item.id"
                  :label="item.propValue"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.propValue }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProb" id="category-prop-select2">
              <span slot="label"><span class="required-icon">{{ ruleForm.subCategoryVal.standardProb }}：</span></span>
              <el-select v-model="ruleForm.attributeVal[1]" :loading="attributeLoading[1]" placeholder="请选择属性" value-key="id" @visible-change="cateProp2ItemShow">
                <el-option
                  v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (2)), false)"
                  :key="item.id"
                  :label="item.propValue"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.propValue }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProc" id="category-prop-select3">
              <span slot="label"><span class="required-icon">{{ ruleForm.subCategoryVal.standardProc }}：</span></span>
              <el-select v-model="ruleForm.attributeVal[2]" :loading="attributeLoading[2]" placeholder="请选择属性" value-key="id" @visible-change="cateProp3ItemShow">
                <el-option
                  v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (3)), false)"
                  :key="item.id"
                  :label="item.propValue"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.propValue }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProd" id="category-prop-select4">
              <span slot="label"><span class="required-icon">{{ ruleForm.subCategoryVal.standardProd }}：</span></span>

              <el-select v-model="ruleForm.attributeVal[3]" :loading="attributeLoading[3]" placeholder="请选择属性" value-key="id" @visible-change="cateProp4ItemShow">
                <el-option
                  v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (4)), false)"
                  :key="item.id"
                  :label="item.propValue"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.propValue }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProe" id="category-prop-select5">
              <span slot="label"><span class="required-icon">{{ ruleForm.subCategoryVal.standardProe }}：</span></span>

              <el-select v-model="ruleForm.attributeVal[4]" :loading="attributeLoading[4]" placeholder="请选择属性" value-key="id" @visible-change="cateProp5ItemShow">
                <el-option
                  v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (5)), false)"
                  :key="item.id"
                  :label="item.propValue"
                  :value="item"
                >
                  <span v-if="item.noDisable">{{ item.propValue }}</span>
                  <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <span slot="label">
                <span v-if="ruleForm.subCategoryVal.categoryUnit" class="required-icon">采购数量({{ ruleForm.subCategoryVal.categoryUnit }})：</span>
                <span v-else class="required-icon">采购数量：</span>
              </span>
              <el-input-number v-model="ruleForm.buyNum" :min="1" :max="100000" :precision="0" label="请输入采购数量" />
            </el-form-item>
          </el-form>
          <button class="search-btn" @click="searchDetail">搜索</button>
        </div>

      </div>
    </div>
    <ChooseMap v-if="showMap" :location="{lat: ruleForm.address.latitude, lng: ruleForm.address.longitude}" @concel="concel" @submitMap="submitMap" />
  </div>
</template>

<script>
import { toProductList, toSearchPage } from '@/js/product'
import ChooseMap from '@/components/ChooseMap'
import { loadMainCategory, loadsubCategory, loadAttribute, loadPropValExistSpu } from '@/api/search/index'
import { Base64 } from 'js-base64'
export default {
  components: {
    ChooseMap
  },
  data() {
    return {
      urlData: {},
      mainCategoryList: [], // 主分类列表
      subCategoryList: [], // 子分类列表
      attributeInfo: [], // 关键属性列表
      attributeLoading: [true, true, true, true, true], // 关键属性下拉框打开时的标志
      ruleForm: {
        mainCategoryVal: {}, // 已选的主分类值
        subCategoryVal: {}, // 已选的子分类值
        attributeVal: [{}, {}, {}, {}, {}], // 所选属性值的id
        address: {}, // 地址
        buyNum: 1 // 采购数量
      },
      showMap: false
    }
  },
  watch: {
    // 地址变化加载主分类
    'ruleForm.address': {
      handler: function() {
        this.getMainCate()
      }
    },
    // 动态加载子分类
    'ruleForm.mainCategoryVal': {
      handler: function(newVal) {
        this.ruleForm.subCategoryVal = {}
        this.ruleForm.attributeVal = [{}, {}, {}, {}, {}]
        this.attributeInfo = []
        this.subCategoryList = []
        if (newVal.id) {
          const lat = this.ruleForm.address.latitude
          const lng = this.ruleForm.address.longitude
          const mainCategoryId = newVal.id
          loadsubCategory({ mainCategoryId, lng, lat }).then(res => {
            if (res.data && res.data.existIds && res.data.existIds.length > 0) {
              res.data.list.forEach(temp => {
                temp.noDisable = res.data.existIds.includes(temp.id)
              })
            } else {
              res.data.list.forEach(temp => { temp.noDisable = false })
            }
            this.subCategoryList = this.sortItem(res.data.list, true)
            if (this.urlData.childCategoryId) {
              const selected = res.data.list.filter(temp => temp.id === this.urlData.childCategoryId)
              this.ruleForm.subCategoryVal = selected && selected.length > 0 ? selected[0] : {}
              delete this.urlData.childCategoryId
            }
          })
        }
      }
    },
    // 动态加载属性
    'ruleForm.subCategoryVal': {
      handler: function(newVal) {
        this.ruleForm.attributeVal = [{}, {}, {}, {}, {}]
        if (newVal.id) {
          loadAttribute(newVal.id).then(res => {
            this.attributeInfo = res.data
            if (newVal.standardProa && this.urlData.proaId) {
              const selected = res.data.filter(temp => temp.id === this.urlData.proaId && temp.propType === 1)[0]
              if (selected) {
                this.ruleForm.attributeVal.splice(0, 1, selected)
              }
              delete this.urlData.proaId
            }
            if (newVal.standardProb && this.urlData.probId) {
              const selected = res.data.filter(temp => temp.id === this.urlData.probId && temp.propType === 2)[0]
              if (selected) {
                this.ruleForm.attributeVal.splice(1, 1, selected)
              }
              delete this.urlData.probId
            }
            if (newVal.standardProc && this.urlData.procId) {
              const selected = res.data.filter(temp => temp.id === this.urlData.procId && temp.propType === 3)[0]
              if (selected) {
                this.ruleForm.attributeVal.splice(2, 1, selected)
              }
              delete this.urlData.procId
            }
            if (newVal.standardProd && this.urlData.prodId) {
              const selected = res.data.filter(temp => temp.id === this.urlData.prodId && temp.propType === 4)[0]
              if (selected) {
                this.ruleForm.attributeVal.splice(3, 1, selected)
              }
              delete this.urlData.prodId
            }
            if (newVal.standardProe && this.urlData.proeId) {
              const selected = res.data.filter(temp => temp.id === this.urlData.proeId && temp.propType === 5)[0]
              if (selected) {
                this.ruleForm.attributeVal.splice(4, 1, selected)
              }
              delete this.urlData.proeId
            }
          })
        } else {
          this.attributeInfo = []
        }
      }
    }

  },
  created() {
    try {
      this.urlData = JSON.parse(Base64.decode(this.$route.params.data))
      if (!this.urlData) {
        this.urlData = {}
      }
    } catch (e) {
      this.urlData = {}
    }
    this.ruleForm.address = this.urlData.address ? this.urlData.address : {}
    this.buyNum = this.urlData.buyNum ? this.urlData.buyNum : 1
    this.getMainCate()
  },
  methods: {
    // 是否展现主分类下拉框
    mainCategoryItemShow(flag) {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      if (flag && (!lat || !lng)) {
        document.getElementById('main-category-select').getElementsByClassName('el-select')[0].click()
        this.$message.error('请先选择收货地址!')
      }
    },
    // 是否展现子分类下拉框
    subCategoryItemShow(flag) {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      if (flag) {
        if (!lat || !lng) {
          document.getElementById('sub-category-select').getElementsByClassName('el-select')[0].click()
          this.$message.error('请先选择收货地址!')
        } else if (!this.ruleForm.mainCategoryVal.id) {
          document.getElementById('sub-category-select').getElementsByClassName('el-select')[0].click()
          this.$message.error('请先选择主分类!')
        }
      }
    },
    // 是否展现属性值1下拉框
    cateProp1ItemShow(flag) {
      this.loadCateProp(0, flag)
    },
    // 是否展现属性值2下拉框
    cateProp2ItemShow(flag) {
      this.loadCateProp(1, flag)
    },
    // 是否展现属性值3下拉框
    cateProp3ItemShow(flag) {
      this.loadCateProp(2, flag)
    },
    // 是否展现属性值4下拉框
    cateProp4ItemShow(flag) {
      this.loadCateProp(3, flag)
    },
    // 是否展现属性值5下拉框
    cateProp5ItemShow(flag) {
      this.loadCateProp(4, flag)
    },
    // 加载属性值
    loadCateProp(index, flag) {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      if (flag) {
        this.$set(this.attributeLoading, index, true)
        if (!lat || !lng) {
          document.getElementById(`category-prop-select${index + 1}`).getElementsByClassName('el-select')[0].click()
          this.$message.error('请先选择收货地址!')
        } else {
          const proaId = this.ruleForm.attributeVal[0].id
          const probId = this.ruleForm.attributeVal[1].id
          const procId = this.ruleForm.attributeVal[2].id
          const prodId = this.ruleForm.attributeVal[3].id
          const proeId = this.ruleForm.attributeVal[4].id
          const mainCategoryId = this.ruleForm.mainCategoryVal.id
          const childCategoryId = this.ruleForm.subCategoryVal.id
          loadPropValExistSpu(index + 1, { mainCategoryId, childCategoryId, lng, lat, proaId, probId, procId, prodId, proeId }).then(res => {
            const data = this.attributeInfo.filter(temp => temp.propType === (index + 1))
            if (res.data) {
              data.forEach(temp => {
                temp.noDisable = res.data.includes(temp.id)
              })
            }
            let temp = {}
            if (this.ruleForm.attributeVal[index].id) {
              temp = data.filter(temp => temp.id === this.ruleForm.attributeVal[index].id)
              temp = temp.length > 0 ? temp[0] : {}
            }
            this.ruleForm.attributeVal.splice(index, 1, temp)
          }).finally(() => {
            this.$set(this.attributeLoading, index, false)
          })
        }
      }
    },

    // 获取主分类列表
    getMainCate() {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      let param = {}
      if (lat && lng) {
        param = { lat, lng }
      }
      loadMainCategory(param).then(res => {
        if (res.data && res.data.existIds && res.data.existIds.length > 0) {
          res.data.list.forEach(temp => {
            temp.noDisable = res.data.existIds.includes(temp.id)
          })
        } else {
          res.data.list.forEach(temp => { temp.noDisable = false })
        }
        this.mainCategoryList = this.sortItem(res.data.list, true)
        if (this.urlData.mainCategoryId) {
          const selected = res.data.list.filter(temp => temp.id === this.urlData.mainCategoryId)
          this.ruleForm.mainCategoryVal = selected && selected.length > 0 ? selected[0] : {}
        }
      })
    },
    // 选择项排序
    sortItem(array, isFlag) {
      array = isFlag ? array : JSON.parse(JSON.stringify(array))
      array.sort((a, b) => {
        return (a.noDisable ? 0 : 1) - (b.noDisable ? 0 : 1)
      })
      return array
    },
    // 关闭地图
    concel() {
      this.showMap = false
    },
    // 选择地址
    submitMap(address) {
      this.ruleForm.address = address
      let end = address.latitude.toString() + ',' + address.longitude.toString()
      this.$store.commit('SEARCH_SITE', end)
      console.log(address, '888 ')
      this.showMap = false
    },
    // 打开地图
    openMap() {
      this.showMap = true
    },
    searchDetail() {
      if (!this.ruleForm.address.latitude || !this.ruleForm.address.longitude) {
        this.$message.error('请点击选择收货地址')
        return
      } else if (!this.ruleForm.mainCategoryVal.id) {
        this.$message.error('请选择主分类')
        return
      } else if (!this.ruleForm.subCategoryVal.id) {
        this.$message.error('请选择子分类')
        return
      } else {
        const subCategoryVal = this.ruleForm.subCategoryVal
        const attributeVal = this.ruleForm.attributeVal
        if (subCategoryVal.standardProa && !attributeVal[0].id) {
          this.$message.error(`请选择${subCategoryVal.standardProa}`)
          return
        } else if (subCategoryVal.standardProb && !attributeVal[1].id) {
          this.$message.error(`请选择${subCategoryVal.standardProb}`)
          return
        } else if (subCategoryVal.standardProc && !attributeVal[2].id) {
          this.$message.error(`请选择${subCategoryVal.standardProc}`)
          return
        } else if (subCategoryVal.standardProd && !attributeVal[3].id) {
          this.$message.error(`请选择${subCategoryVal.standardProd}`)
          return
        } else if (subCategoryVal.standardProe && !attributeVal[4].id) {
          this.$message.error(`请选择${subCategoryVal.standardProe}`)
          return
        }
      }
      const sortType = 0
      const address = this.ruleForm.address
      const mainCategoryId = this.ruleForm.mainCategoryVal.id
      const childCategoryId = this.ruleForm.subCategoryVal.id
      const mainCategory = this.ruleForm.mainCategoryVal
      const childCategory = this.ruleForm.subCategoryVal
      const proaId = this.ruleForm.attributeVal[0].id
      const probId = this.ruleForm.attributeVal[1].id
      const procId = this.ruleForm.attributeVal[2].id
      const prodId = this.ruleForm.attributeVal[3].id
      const proeId = this.ruleForm.attributeVal[4].id
      const buyNum = this.buyNum
      const searchRange = 50
      const info = {}
      info.proa = this.ruleForm.attributeVal[0].propValue
      info.prob = this.ruleForm.attributeVal[1].propValue
      info.proc = this.ruleForm.attributeVal[2].propValue
      info.prod = this.ruleForm.attributeVal[3].propValue
      info.proe = this.ruleForm.attributeVal[4].propValue
      // 更新地址栏
      toSearchPage(this, { address, buyNum, mainCategoryId, childCategoryId, proaId, probId, procId, prodId, proeId }, true)
      toProductList(this, { sortType, childCategory, mainCategory, proaId, probId, procId, prodId, proeId, address, buyNum, searchRange, info })
    }
  }
}
</script>

<style lang='scss' scoped >
.search {
  background: #f5f5f5;
  .container {
    .corner {
      margin-top: 8px;
    }
    .search-box {
      background: #ffffff;
      margin: 8px 0 60px 0;
      padding: 60px 0;
      display: flex;
      justify-content: center;
      .required-icon{
        &::before{
          content: '*';
          color: #ff4949;
          margin-right: 4px;
        }
      }
        .search-btn{
            width: 400px;
            height: 42px;
            line-height: 42px;
            text-align: center;
            background: #FF3B30;
            color: #ffffff;
            border-radius: 3px;
            margin-left: 105px;
            font-size: 18px;
            cursor: pointer;
        }
      .site{
        font-size: 20px;
          color: #C7C7CC;
      }
    }
  }
    /deep/ .input{
        .el-input{
            width: 400px;
        }
    }
    /deep/ .search-box{
        .el-select{
            width: 400px;
        }
        .el-form-item__label{
            width: 130px !important;
        }
    }
    /deep/ .search-box{
        .el-form-item{
            width: 508px;
        }
    }
    /deep/ .range{
        .el-input{
            width: 180px;
        }
    }
}
</style>
